// ignore_for_file: slash_for_doc_comments

import 'package:enjoy_plus/utils/fluttertoast.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:enjoy_plus/utils/logger.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

class LocationList extends StatefulWidget {
  const LocationList({super.key});

  @override
  State<LocationList> createState() => _LocationListState();
}

class _LocationListState extends State<LocationList> {
  String key = 'e72eb0f39643b1a12ce9222ce863cd6c';
  String baseUrl = 'https://restapi.amap.com/v3';
  String address = '';
  // 附近社区
  List nearbyCommunities = [];
  // 地址解析
  // 文本位置信息 -> 经纬度

  // 逆地址解析
  // 经纬度 -> 文本位置信息

  // https://restapi.amap.com/v3/geocode/regeo?location=116.310003,39.991957&key=必传

  @override
  void initState() {
    // 请求位置权限
    requestLocationPermission();
    //逆地址解析
    reverseGeocoding(121.521763, 31.234034);
    // 周边社区
    queryNearbyCommunities(121.521763, 31.234034);
    super.initState();
  }

  Future<void> requestLocationPermission() async {
    PermissionStatus status = await Permission.location.request();
    if (status.isGranted) {
      // 权限授予
      ToastUtil.showSuccess('位置权限授予');
    } else {
      // 权限未授予
      ToastUtil.showError('位置权限未授予, 请去设置中心开启');
    }
  }

/**
 * 异步获取当前设备的位置信息。
 * 
 * 此方法首先根据设备的平台（Android、iOS/macOS 或 Web）配置不同的定位设置，
 * 然后使用这些设置获取设备的当前位置，并处理位置信息或异常。
 */
  Future<void> getCurrentLocation() async {
    late LocationSettings locationSettings;

    if (defaultTargetPlatform == TargetPlatform.android) {
      // 针对Android平台，设置高精度定位、100米距离过滤、强制使用位置管理器等
      locationSettings = AndroidSettings(
          accuracy: LocationAccuracy.high,
          distanceFilter: 100,
          forceLocationManager: true,
          intervalDuration: const Duration(seconds: 10),
          foregroundNotificationConfig: const ForegroundNotificationConfig(
            notificationText:
                "Example app will continue to receive your location even when you aren't using it",
            notificationTitle: "Running in Background",
            enableWakeLock: true,
          ));
    } else if (defaultTargetPlatform == TargetPlatform.iOS ||
        defaultTargetPlatform == TargetPlatform.macOS) {
      // 针对iOS和macOS平台，设置高精度定位、健身活动类型、100米距离过滤等
      locationSettings = AppleSettings(
        accuracy: LocationAccuracy.high,
        activityType: ActivityType.fitness,
        distanceFilter: 100,
        pauseLocationUpdatesAutomatically: true,
        // 只有在应用在后台启动时才设置为true
        showBackgroundLocationIndicator: false,
      );
    } else if (kIsWeb) {
      // 针对Web环境，设置高精度定位、100米距离过滤、5分钟的最大年龄等
      locationSettings = WebSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
        maximumAge: const Duration(minutes: 5),
      );
    } else {
      // 对于其他平台，默认设置高精度定位和100米距离过滤
      locationSettings = const LocationSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
      );
    }

    // supply location settings to getCurrentPosition
    try {
      Position position = await Geolocator.getCurrentPosition(
          locationSettings: locationSettings);
      logger.e(position);
      ToastUtil.showSuccess(
          '位置信息 - 纬度${position.latitude} - 经度 ${position.longitude}');
    } catch (e) {
      ToastUtil.showError('位置获取失败');
    }
  }

  // 逆地址解析
  Future<void> reverseGeocoding(double longitude, double latitude) async {
    String url =
        '$baseUrl/geocode/regeo?location=$longitude,$latitude&key=$key';
    try {
      final res = await http.get(url);
      setState(() {
        address = res['regeocode']['formatted_address'];
      });
    } catch (e) {
      ToastUtil.showError('地址解析失败');
    }
  }

//获取周边小区信息
  Future<void> queryNearbyCommunities(double latitude, double longitude) async {
    String url = '$baseUrl/place/around?key=$key&location=$longitude,$latitude';
    try {
      final res = await http.get(url);
      for (var element in (res['pois'] as List)) {
        setState(() {
          nearbyCommunities.add(element['name']);
        });
      }
    } catch (e) {
      ToastUtil.showError('周边社区获取失败');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('选择社区'),
        ),
        body: ListView(
          padding: const EdgeInsets.all(10),
          children: [
            const Row(
              children: [
                Text(
                  '当前地址',
                  style: TextStyle(color: Colors.grey),
                )
              ],
            ),
            const SizedBox(height: 10),
            Container(
              color: Colors.white,
              padding: const EdgeInsets.all(10),
              child: Row(
                children: [
                  Expanded(child: Text(address)),
                  const Row(
                    children: [
                      Icon(Icons.location_searching_outlined,
                          color: Colors.blue),
                      SizedBox(width: 2),
                      Text(
                        '重新定位',
                        style: TextStyle(color: Colors.blue),
                      ),
                    ],
                  )
                ],
              ),
            ),
            const SizedBox(height: 10),
            const Row(
              children: [
                Text(
                  '附近社区',
                  style: TextStyle(color: Colors.grey),
                )
              ],
            ),
            const SizedBox(height: 10),
            ListView(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                children: nearbyCommunities.map((item) {
                  return GestureDetector(
                      onTap: () {
                        Navigator.pushNamed(context, '/building_list',
                            arguments: {'point': item});
                      },
                      child: Container(
                          color: Colors.white,
                          padding: const EdgeInsets.all(10),
                          child: Row(children: [
                            Expanded(child: Text(item)),
                            const Row(children: [
                              Icon(
                                Icons.arrow_forward_ios,
                                size: 16,
                                color: Colors.black,
                              ),
                            ])
                          ])));
                }).toList())
          ],
        ));
  }
}
